òɾۿûѧϰʹá
ԭַhttps://www.joinquant.com/post/11103

ԭһ˵ʽ鵽ԭĺ߽ۡ


ԭĲԴ£

#Ծۿ

import talib
import pandas as pd
import numpy as np
import math
from sklearn.svm import SVR  
from sklearn.model_selection import GridSearchCV  
from sklearn.model_selection import learning_curve


def initialize(context):
    # ƱÿʽʱǣʱӶ֮ʱӶ֮ǧ֮һӡ˰, ÿʽӶͿ5Ǯ
    set_order_cost(OrderCost(close_tax=0.000, open_commission=0.0000, close_commission=0.0000, min_commission=0), type='stock')
    # 趨Ϊ̶ֵ
    set_slippage(FixedSlippage(0.00))
    
    # һȫֱ, Ҫ֤ȯ                                                                                           
    context.stocks = ['399300.XSHE']
    # ҪĹƱ
    set_universe(context.stocks)

    
# ʼ˲
def handle_data(context, data):
    # ȡõǰֽ
    cash = context.portfolio.cash
    # ѭƱб
    for stock in context.stocks:
        # ȡƱ
        h = attribute_history(stock, 60, '1d', ('high','low','close'))
        # STOCHźţ߼ۣͼۣ̼ۺͿߣһȡΪ9
        # ע⣺STOCHʹõpricenarray
        slowk, slowd = talib.STOCH(h['high'].values,h['low'].values,h['close'].values,
                                            fastk_period=17,slowk_period=9,
                                            slowk_matype=0,slowd_period=7,slowd_matype=0)
        # kdֵ
        
        print(slowk)
        # print(slowk[-6:-1])
        # MA_stoch_5 = slowk[-5:].mean()
        
        # print(MA_stoch_5)
        # MA_stoch_now=slowk[-1]
        # ȡǰƱ
        current_position = context.portfolio.positions[stock].amount
        # ȡǰƱ۸
        current_price = data[stock].price
        # slowk > 90 or slowd > 90ӵеĹƱ>=0ʱйƱ
        if (slowk[-1] < 80 and slowk[-2] > 80 and current_position >= 0) or (slowk[-1] > 20 and slowk[-1] < 80 and slowk[-1] < slowd[-1] and current_position >= 0):
            order_target(stock, 0)
        # slowk < 10 or slowd < 10, ӵеĹƱ<=0ʱȫ
        elif (slowk[-1] > 20 and slowk[-2] < 20 and current_position <= 0) or (slowk[-1] > 20 and slowk[-1] > 80 and slowk[-1] > slowd[-1] and current_position <= 0):
            # Ʊ
            order_value(stock, cash)
            # ¼
            log.info("Buying %s" % (stock))
